package com.wisdomech.server.service;


import com.wisdomech.server.entity.CardInfo;
import com.wisdomech.server.entity.UrlList;
import com.wisdomech.server.respository.CardInfoRepository;
import com.wisdomech.server.respository.UrllistRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: tubashu
 * @Date: 2018/8/9 23:30
 * @email: tubashu@mail.ru
 */
@Component
public class CardProcessor implements PageProcessor {

    @Autowired
    private UrllistRepository urllistRepository;

    @Autowired
    private CardInfoRepository cardInfoRepository;

    private static CardProcessor cardProcessor;

    private static int index = 66698;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        cardProcessor = this;
        cardProcessor.urllistRepository = this.urllistRepository;
        cardProcessor.cardInfoRepository = this.cardInfoRepository;
    }


    private Site site = Site.me()
            .setRetryTimes(3)
            .setSleepTime(1000)
            .setTimeOut(6000)
            .addHeader("Accept-Encoding", "/")
            .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36");


    @Override
    public void process(Page page) {
        boolean getInfo = true;
        if (getInfo) {//获取实际内容
            List<String> lists = new ArrayList<>();
            UrlList urlList = cardProcessor.urllistRepository.findById(index);
            index++;
            if (urlList != null) {
                lists.add(urlList.getUrl());
            }
            urlList = cardProcessor.urllistRepository.findById(index);
            index++;
            if (urlList != null) {
                lists.add(urlList.getUrl());
            }
            page.addTargetRequests(lists);
//            lists.add(urlList.getUrl());
//            page.addTargetRequests(lists);
            if (page.getHtml().xpath("//span[@style='width:140px;color:#8ec31f;']/text()").all().size() == 2) {
                String phone = page.getHtml().xpath("//span[@style='width:140px;color:#8ec31f;']/text()").all().get(1).trim();
                if(phone.length()==11) {
                    if (cardProcessor.cardInfoRepository.findByPhone(phone) == null) {
                        String imgurl = page.getUrl().toString();
                        UrlList urlList1 = cardProcessor.urllistRepository.findByUrl(imgurl);
                        if(urlList1!=null) {

                            CardInfo cardInfo = new CardInfo();
                            String erweima = page.getHtml().xpath("//div[@class='iframe']/img/@src").toString();


                            String erweimaname = getRandomStr(12) + ".jpg";
                            String img = getRandomStr(12) + ".jpg";
                            cardInfo.setQrcode(erweimaname);
                            cardInfo.setHeadimg(img);


                            download(erweima, erweimaname, "E:\\imgerweima");
                            download(urlList1.getImg(), img, "E:\\imgweixin");

                            cardInfo.setRealname(page.getHtml().xpath("//li[@style='border-bottom:1px dashed #ededed; text-align:center;line-height:34px;']/span/b/text()").toString().trim());
                            cardInfo.setJieshao(page.getHtml().xpath("//span[@class='des_info_text2']/text()").toString().trim());
                            cardInfo.setShuxing(page.getHtml().xpath("//a[@class='btnCity']/text()").toString().trim());
                            cardInfo.setDiqu(page.getHtml().xpath("//li[@style='width:190px;height: 40px']/a/text()").toString().trim());
                            cardInfo.setWeixin(page.getHtml().xpath("//span[@class='des_info_text2'][2]/text()").toString().trim());
                            cardInfo.setPhone(page.getHtml().xpath("//span[@style='width:140px;color:#8ec31f;']/text()").all().get(1).trim());
                            Random random = new Random();
                            cardInfo.setShowcount(random.nextInt(1200));
                            cardInfo.setCreatedate(new Date());

                            page.putField("info", cardInfo);
                        }
                    }
                }
            }
        } else {//获取网址列表
            List<String> list = page.getHtml().xpath("//div[@class='pageNo vm center']/a").links().all();
            page.addTargetRequests(list);
            List<String> urls = page.getHtml().xpath("//p[@class='goods_name ellips']/a").links().all();
            List<String> imgs = page.getHtml().xpath("//div[@class='border5']/a/img/@src").all();
            page.putField("link", urls);
            page.putField("imgs", imgs);
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public void download(String urlString, String filename, String savePath) {
        // 构造URL
        try {
            URL url = new URL(urlString);          // 打开连接
            URLConnection con = url.openConnection();          //设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf = new File(savePath);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //生成指定长度的随机字符串
    public static String getRandomStr(int length) {
        String base = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        int randomNum;
        char randomChar;
        Random random = new Random();
        // StringBuffer类型的可以append增加字符
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < length; i++) {
            // 可生成[0,n)之间的整数，获得随机位置
            randomNum = random.nextInt(base.length());
            // 获得随机位置对应的字符
            randomChar = base.charAt(randomNum);
            // 组成一个随机字符串
            str.append(randomChar);
        }
        return str.toString();
    }
}

